package com.fy.module.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fy.common.consts.ExamContant;
import com.fy.common.dto.PageDto;
import com.fy.common.enums.ApiErrorEnum;
import com.fy.common.exception.ServiceException;
import com.fy.common.vo.ApiRest;
import com.fy.common.vo.PageResult;
import com.fy.module.exam.dto.ExamSaveDto;
import com.fy.module.exam.vo.ExamUpdateVo;
import com.fy.module.exam.entity.Exam;
import com.fy.module.exam.entity.ExamDepart;
import com.fy.module.exam.entity.ExamRepo;
import com.fy.module.exam.entity.ExamUser;
import com.fy.module.exam.mapper.ExamDepartMapper;
import com.fy.module.exam.mapper.ExamMapper;
import com.fy.module.exam.mapper.ExamRepoMapper;
import com.fy.module.exam.mapper.ExamUserMapper;
import com.fy.module.exam.service.IExamService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.module.repo.entity.Repo;
import com.fy.module.repo.service.IRepoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author yang
 * @since 2023-03-22
 */
@Service
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements IExamService {
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private ExamRepoMapper examRepoMapper;
    @Autowired
    private ExamDepartMapper examDepartMapper;
    @Autowired
    private ExamUserMapper examUserMapper;
    @Autowired
    private IRepoService repoService;

    @Override
    public ApiRest create(ExamSaveDto examSaveDto) {
        checkData(examSaveDto);

        //save exam
        Exam exam = new Exam();
        BeanUtil.copyProperties(examSaveDto, exam, true);
        exam.setId(IdWorker.getIdStr());
        exam.setUpdateTime(new Date());
        exam.setCreateTime(new Date());
        exam.setJoinType(ExamContant.ZUJUAN_TYPE_REPO);
        exam.setState(ExamContant.OPEN);
        this.baseMapper.insert(exam);

        //save exam repo
        examSaveDto.getExamRepos().forEach(item -> {
            item.setId(IdWorker.getIdStr());
            item.setExamId(exam.getId());
            examRepoMapper.insert(item);
        });

        //save exam depart
        if (examSaveDto.getOpenType() == ExamContant.OPENT_DEPART) {//部门公开
            examSaveDto.getDepartIds().forEach(item -> {
                ExamDepart examDepart = new ExamDepart();
                examDepart.setExamId(exam.getId());
                examDepart.setDepartId(item);
                examDepart.setId(IdWorker.getIdStr());
                examDepartMapper.insert(examDepart);
            });
        }

        //save exam user
        if (examSaveDto.getOpenType() == ExamContant.OPENT_SPECIFY) {//指定人员
            examSaveDto.getUserIds().forEach(item -> {
                ExamUser examUser = new ExamUser();
                examUser.setId(IdWorker.getIdStr());
                examUser.setExamId(exam.getId());
                examUser.setUserId(item);
                examUserMapper.insert(examUser);
            });
        }

        return ApiRest.success();
    }

    @Override
    public PageResult findPage(PageDto<Exam> pageDto) {
        if (pageDto == null) {
            throw new ServiceException("参数异常");
        }
        if (pageDto.getNow() <= 0) {
            throw new ServiceException("参数异常");
        }
        if (pageDto.getWhere() == null) {
            throw new ServiceException("参数异常");
        }
        //设置分页
        IPage<Exam> page = new Page<>(pageDto.getNow(), pageDto.getSize());
        //条件构造器
        IPage pageInfo = examMapper.findExamByPage(page, pageDto.getWhere());

        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setList(pageInfo.getRecords());
        pageResult.setPages(pageInfo.getPages());
        return pageResult;
    }

    /**
     * 根据考试id获取考试
     *
     * @param id
     * @return
     */
    @Override
    public ApiRest getExamById(String id) {
        //先查询出来考试记录
        Exam exam = examMapper.selectById(id);
        //然后查询考试关联的题库id 数组,然后根据这个数组的id来逐一找出所有的题库
        List<ExamRepo> examRepoList = examRepoMapper.selectRepoIds(exam.getId());
        List<Repo> repoList = null;
        if (examRepoList != null && !examRepoList.isEmpty()) {
            repoList = new ArrayList<>();
            for (ExamRepo examRepo : examRepoList) {
                //根据题库id查找题库的信息,然后放入返回的数组中
                Repo repo = repoService.getById(examRepo.getRepoId());
                if (repo != null) repoList.add(repo);
            }
        }
        //TODO：完成数据回显
        //查找考试关联的开发部门

        //考试关联的人员信息

        //最后封装整个组卷信息
        ExamUpdateVo examUpdateVo = new ExamUpdateVo();
        BeanUtil.copyProperties(exam, examUpdateVo);
        examUpdateVo.setExamRepos(examRepoList);
        examUpdateVo.setRepoList(repoList);
        return ApiRest.success(examUpdateVo);
    }

    private void checkData(ExamSaveDto examSaveDto) {
        if (examSaveDto == null) {
            throw new ServiceException("参数不能为空");
        }
        if (StringUtils.isEmpty(examSaveDto.getTitle())) {
            throw new ServiceException(ApiErrorEnum.EXAM_CONTENT_IS_NULL);
        }

        //todo ...

    }
}
